/*
* // +-------------------------------------------------------------------------------------------------
* // |                 有你就好 [ 有节骨乃坚，无心品自端 ]     <http://encoding.wang>
* // +-------------------------------------------------------------------------------------------------
* // |                             独在异乡为异客         每逢佳节倍思亲
* // +-------------------------------------------------------------------------------------------------
* // |                 联系:   <707069100@qq.com>      <http://weibo.com/513778937>
* // +-------------------------------------------------------------------------------------------------
*/

// -----------------------------------------------------------------------------------------------------
// +----------------------------------------------------------------------------------------------------
// |                   ErYang出品 属于小极品          共同学习    共同进步
// +----------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------


package wang.encoding.mroot.service.system.impl

import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.cache.annotation.CacheConfig
import org.springframework.cache.annotation.Cacheable
import org.springframework.stereotype.Service
import wang.encoding.mroot.common.service.BaseServiceImpl
import wang.encoding.mroot.common.util.HibernateValidationUtil
import wang.encoding.mroot.mapper.system.RuleMapper
import wang.encoding.mroot.model.entity.system.Rule
import wang.encoding.mroot.model.enums.StatusEnum
import wang.encoding.mroot.service.system.RuleService
import java.math.BigInteger
import java.time.Instant
import java.util.*
import javax.cache.Cache
import kotlin.collections.ArrayList


/**
 * 权限 service 实现类
 *
 * @author ErYang
 */
@Service
@CacheConfig(cacheNames = ["ruleCache"])
class RuleServiceImpl : BaseServiceImpl<RuleMapper, Rule>(), RuleService {

    companion object {
        /**
         * logger
         */
        private val logger: Logger = LoggerFactory.getLogger(RuleServiceImpl::class.java)
        /**
         * 逗号
         */
        private const val COMMA_NAME: String = ","
    }

    @Autowired
    //@Qualifier("ruleCache")
    private lateinit var ruleCache: Cache<Any, Any>

    /**
     * 初始化新增 Rule 对象
     *
     * @param rule Rule
     * @return Rule
     */
    override fun initSaveRule(rule: Rule): Rule {
        rule.status = StatusEnum.NORMAL.key
        rule.gmtCreate = Date.from(Instant.now())
        return rule
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 初始化修改 Rule 对象
     *
     * @param rule Rule
     * @return Rule
     */
    override fun initEditRule(rule: Rule): Rule {
        rule.gmtModified = Date.from(Instant.now())
        return rule
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * Hibernate Validation 验证
     */
    override fun validationRule(rule: Rule): String? {
        return HibernateValidationUtil.validateEntity(rule)
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 根据 id 查询 Rule 缓存
     *
     * @param id ID
     * @return Rule
     */
    @Cacheable(key = "#id")
    override fun getById2Cache(id: BigInteger): Rule? {
        return super.getById(id)
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 新增 权限
     *
     * @param rule Rule
     * @return ID  BigInteger
     */
    override fun saveBackId(rule: Rule): BigInteger? {
        val id: Int? = super.save(rule)
        if (null != id && 0 < id) {
            return rule.id
        }
        return null
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 删除 权限(更新状态)
     *
     * @param id BigInteger
     * @return ID  BigInteger
     */
    override fun removeBackId(id: BigInteger): BigInteger? {
        val rule = Rule()
        rule.id = id
        rule.status = StatusEnum.DELETE.key
        rule.gmtModified = Date.from(Instant.now())
        val backId: Int? = super.remove2StatusById(rule)
        if (null != backId && 0 < backId) {
            return id
        }
        return null
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 恢复 权限 (更新状态)
     *
     * @param id BigInteger
     * @return ID  BigInteger
     */
    override fun recoverBackId(id: BigInteger): BigInteger? {
        val rule = Rule()
        rule.id = id
        rule.status = StatusEnum.NORMAL.key
        rule.gmtModified = Date.from(Instant.now())
        val backId: Int? = super.recover2StatusById(rule)
        if (null != backId && 0 < backId) {
            return id
        }
        return null
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 更新 权限
     *
     * @param rule Rule
     * @return ID  BigInteger
     */
    override fun updateBackId(rule: Rule): BigInteger? {
        val flag: Boolean = super.updateById(rule)
        if (flag) {
            return rule.id
        }
        return null
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 根据 url 地址查询权限
     *
     * @param url 地址
     * @return Rule
     */
    override fun getByUrl(url: String): Rule? {
        val rule = Rule()
        rule.url = url
        val ruleResult: Rule? = super.getByModel(rule)
        return if (null != ruleResult) {
            return ruleResult
        } else {
            null
        }
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 根据 名称 查询权限
     *
     * @param title 名称
     * @return Rule
     */
    override fun getByTitle(title: String): Rule? {
        val rule = Rule()
        rule.title = title
        val ruleResult: Rule? = super.getByModel(rule)
        return if (null != ruleResult) {
            return ruleResult
        } else {
            null
        }
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 根据角色 id 查询权限
     *
     * @param roleId 角色id
     * @return Set<Rule>
     */
    override fun listByRoleId(roleId: BigInteger): TreeSet<Rule>? {
        return superMapper?.listByRoleId(roleId)
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 根据角色 id 查询权限 id
     *
     * @param roleId 角色id
     * @return id 集合字符串
     */
    override fun listIdByRoleId2String(roleId: BigInteger): String? {
        val list: TreeSet<Rule>? = superMapper?.listByRoleIdAndPidGt0(roleId)
        if (null != list && list.isNotEmpty()) {
            val stringBuffer = StringBuilder()
            stringBuffer.append("")
            val listSize: Int = list.size
            for ((i: Int, rule: Rule) in list.withIndex()) {
                stringBuffer.append(rule.id)
                if (i != listSize - 1) {
                    stringBuffer.append(COMMA_NAME)
                }
            }
            return stringBuffer.toString()
        }
        return null
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 得到 pid 大于 0、类型小于 4 权限集合
     *
     * @return List<Rule>
     */
    override fun listPidGt0AndTypeLt4(): List<Rule>? {
        val list: List<Rule>? = superMapper!!.listPidGt0AndTypeLt4()
        if (null != list && list.isNotEmpty()) {
            return Rule.list2Tree(list)!!
        }
        return null
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 得到 pid 大于 0 权限集合
     *
     * @return List<Rule>
     */
    override fun listPidGt0(): List<Rule>? {
        val list: List<Rule>? = superMapper!!.listPidGt0()
        if (null != list && list.isNotEmpty()) {
            return Rule.list2Tree(list)!!
        }
        return null
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 得到 pid 大于 0 权限集合
     *
     * @return List<Rule>
     */
    override fun list2RoleByRoleIdAndPidGt0(roleId: BigInteger): List<Rule>? {
        val list: List<Rule>? = superMapper!!.list2RoleByRoleIdAndPidGt0(roleId)
        if (null != list && list.isNotEmpty()) {
            return Rule.list2Tree(list)!!
        }
        return null
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 根据 角色 id 和 权限 id 批量新增 角色-权限 表
     *
     * @param roleId BigInteger
     * @param ruleIdArray Array<BigInteger>
     *
     * @return Int
     */
    override fun saveBatchByRoleIdAndRuleIdArray(roleId: BigInteger,
                                                 ruleIdArray: Array<BigInteger>): Int? {
        val params = HashMap<String, Any>()
        params["roleId"] = roleId
        params["ruleIdArray"] = ruleIdArray
        return superMapper?.saveBatchByRoleIdAndRuleIdArray(params)
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 根据 角色 id 和 权限 id 批量删除 角色-权限
     *
     * @param roleId BigInteger
     * @param ruleIdArray Array<BigInteger>
     *
     * @return Int
     */
    override fun removeBatchByRoleIdAndRuleIdArray(roleId: BigInteger,
                                                   ruleIdArray: Array<BigInteger>?): Int? {
        val params = HashMap<String, Any>()
        params["roleId"] = roleId
        if (null != ruleIdArray && ruleIdArray.isNotEmpty()) {
            params["ruleIdArray"] = ruleIdArray
        }
        return superMapper?.removeBatchByRoleIdAndRuleIdArray(params)
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 根据 角色id 删除 角色-权限
     *
     * @param roleId 角色id
     * @return Int
     */
    override fun removeByRoleId(roleId: BigInteger): Int? {
        return superMapper?.removeByRoleId(roleId)
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 根据 角色id 删除 角色-权限
     *
     * @param roleIdArray Array<BigInteger>
     * @return Int
     */
    override fun removeByRoleIdArray(roleIdArray: ArrayList<BigInteger>?): Int? {
        val params = HashMap<String, Any>()
        if (null != roleIdArray && roleIdArray.isNotEmpty()) {
            params["roleIdArray"] = roleIdArray
        }
        return superMapper?.removeByRoleIdArray(params)
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 根据 pid 查询权限
     *
     * @param pid BigInteger
     * @return List<Rule>
     */
    override fun listByPid(pid: BigInteger): List<Rule>? {
        val rule = Rule()
        rule.pid = pid
        return super.listByT(rule)
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 根据 pid 查询 权限集合
     *
     * @param pidArray  ArrayList<BigInteger>
     * @return List<Rule>
     */
    override fun listByPidArray(pidArray: ArrayList<BigInteger>?): List<Rule>? {
        val params = HashMap<String, Any>()
        if (null != pidArray && pidArray.isNotEmpty()) {
            params["pidArray"] = pidArray
        }
        return superMapper?.listByPidArray(params)
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 根据 id 移除 Rule 缓存
     *
     * @param id BigInteger
     *
     */
    override fun removeCacheById(id: BigInteger) {
        val rule: Rule? = this.getById(id)
        if (null != rule) {
            ruleCache.remove(rule.id)
        }
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 根据 id 批量移除　Rule　缓存
     *
     * @param idArray ArrayList<BigInteger>
     *
     */
    override fun removeBatchCacheById(idArray: ArrayList<BigInteger>) {
        if (idArray.isNotEmpty()) {
            for (id: BigInteger in idArray) {
                this.removeCacheById(id)
            }
        }
    }

    // -------------------------------------------------------------------------------------------------

}

// -----------------------------------------------------------------------------------------------------

// End RuleServiceImpl class

/* End of file RuleServiceImpl.kt */
/* Location: ./src/main/kotlin/wang/encoding/mroot/service/system/RuleServiceImpl.kt */

// -----------------------------------------------------------------------------------------------------
// +----------------------------------------------------------------------------------------------------
// |                           ErYang出品 属于小极品  O(∩_∩)O~~   共同学习    共同进步
// +----------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------
